import { login, logout } from '@/api/user'
export default {
  state: {
    user: [
      {
        username: '',
        token: '',
        isLogin: false
        // user: JSON.parse(localStorage.getItem('user')) || []
      }
    ]
  },
  mutations: {
    login (state, payload) {
      state.username = payload.username
      state.token = payload.token
      state.isLogin = true
    },
    logout (state) {
      state.username = ''
      state.token = ''
      state.isLogin = false
    }
  },
  actions: {
    loginAsync (context, payload) {
      const { username, password } = payload
      // 调用登录api方法
      return login(username, password).then(res => {
        // 在 action 中不能直接更新状态，而是提交 mutation 来更新状态
        context.commit('login', res)
        return {
          isLogin: true
        }
      }).catch(e => console.log(e))
    },
    logoutAsync (context) {
      return logout().then(res => {
        context.commit('logout')
        return res
      })
    }
  },
  getters: {}
}
